import Vue from "vue";
import Vuex from "vuex";
import request from "../http/request";
import UserInfo from "@/model/UserInfo";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    token: window.sessionStorage.getItem("token"),
    userInfo: null,
  },
  mutations: {
    setToken(state, token) {
      state.token = token;
      window.sessionStorage.setItem("token", token);
    },
    removeToken(state) {
      state.token = "";
      state.userInfo = null;
      window.sessionStorage.removeItem("token");
    },
    setUserInfo(state, userInfo) {
      const info: any = UserInfo.create(userInfo);
      state.userInfo = info;
    },
  },
  actions: {
    getUserInfo(context) {
      const token = context.state.token;
      if (token) {
        request
          .getUserInfo(token)
          .then((res) => {
            if (res.data.code === 0) {
              context.commit("setUserInfo", res.data.data);
            } else {
              context.commit("removeToken");
            }
          })
          .catch((err) => {
            context.commit("removeToken");
          });
      }
    },
  },
  modules: {},
});
